package com.doge.calcalbum.business.entry

import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import androidx.activity.viewModels
import androidx.core.view.isVisible
import androidx.core.view.setPadding
import androidx.recyclerview.widget.GridLayoutManager
import com.doge.calcalbum.R
import com.doge.calcalbum.analysis.*
import com.doge.calcalbum.business.ITEM_CHECK
import com.doge.calcalbum.business.album.AlbumRepository
import com.doge.calcalbum.business.account.AccountHelper.self
import com.doge.calcalbum.business.album.migrate.AlbumMigrateDialogFragment
import com.doge.calcalbum.business.album.migrate.AlbumMigrateDialogViewModel
import com.doge.calcalbum.business.guide.GuideAlbum2Layout
import com.doge.calcalbum.business.guide.GuideAlbum3Layout
import com.doge.calcalbum.business.sysalbum.SysAlbumActivity
import com.doge.calcalbum.business.vip.VipHelper
import com.doge.calcalbum.core.BaseActivity
import com.doge.calcalbum.core.base.adapters.ITEM_CLICKED
import com.doge.calcalbum.core.base.adapters.ITEM_LONG_CLICKED
import com.doge.calcalbum.databinding.ActivityEntryBinding
import com.doge.calcalbum.db.model.Album
import com.doge.calcalbum.db.model.Entry
import com.doge.calcalbum.utils.*
import com.doge.calcalbum.widgets.GridItemDecoration
import com.doge.calcalbum.widgets.viewer.TransitionViewsRef
import com.doge.calcalbum.widgets.viewer.TransitionViewsRef.KEY_ENTRY
import com.doge.calcalbum.widgets.viewer.ViewerHelper
import kotlin.math.min

class EntryActivity : BaseActivity() {
    private val binding by lazy { ActivityEntryBinding.inflate(layoutInflater) }
    private val albumId by lazy { intent.getIntExtra(EXTRA_ALBUM_ID, Album.DEFAULT_PICTURE_ID) }
    private val albumType by lazy { intent.getIntExtra(EXTRA_ALBUM_TYPE, Album.TYPE_PICTURE) }
    private val dialogViewModel by viewModels<AlbumMigrateDialogViewModel>()
    private val viewModel by viewModels<EntryViewModel> { EntryViewModelFactory(albumId) }
    private val adapter by lazy { EntryAdapter() }
    private var dataList: List<Entry>? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        systemWindowInsetsTop.observe(this) {
            binding.fitsSys.setPadding(it / 2)
        }

        initialViews()
        binding.emptyText.setText(if (albumType == Album.TYPE_VIDEO) R.string.empty_video else R.string.empty_picture)
        binding.recyclerView.itemAnimator = null
        val itemDecoration = object : GridItemDecoration(2.dp, Color.TRANSPARENT) {
            override fun getItemSidesIsHaveOffsets(itemPosition: Int) =
                arrayOf(itemPosition % 4 != 0, true, itemPosition % 4 != 3, true)
        }
        binding.recyclerView.addItemDecoration(itemDecoration)
        binding.recyclerView.layoutManager = GridLayoutManager(binding.recyclerView.context, 4)
        binding.recyclerView.adapter = adapter
        adapter.setListener(::handleAdapterCallback)
        viewModel.album.observe(this) {
            binding.pageTitle.text = it?.title
        }
        viewModel.entryList.observe(this) {
            dataList = it
            if (dataList.isNullOrEmpty()) animToNormalMode()
            binding.empty.isVisible = dataList.isNullOrEmpty()
            adapter.submitList(it)
        }
        dialogViewModel.selectedEvent.observe(this) {
            moveSelectedToAlbum(it)
        }

        GuideAlbum2Layout.attach(binding.root)
    }

    private fun moveSelectedToAlbum(target: Album?) {
        if (target == null) return
        val selected = adapter.selected
        if (selected.isEmpty()) return
        viewModel.moveToAlbum(selected, target.id)
    }

    private fun handleAdapterCallback(action: String, item: Any?) {
        when (action) {
            ITEM_CLICKED -> showViewer(item as? Entry?)
            ITEM_LONG_CLICKED -> animToEditMode(item as? Entry?)
            ITEM_CHECK -> adapter.switch(item as? Entry?)
        }
    }

    private fun initialViews() {
        binding.pageBack.setOnClickCallback { onBackPressed() }
        binding.add.setOnClickCallback {
//            if (self.canGetFreeVip == 1) {
//                VipHelper.showGetFreeVipDialog()
//            } else
                SysAlbumActivity.start(this, albumId, albumType)
        }
        binding.edit.setOnClickCallback {
            animToEditMode()
        }
        binding.editCancel.setOnClickCallback {
            animToNormalMode()
        }
        binding.selectAll.setOnClickCallback {
            adapter.switchAll()
        }
        binding.delete.setOnClickCallback {
            val selected = adapter.selected
            if (selected.isEmpty()) {
                toast(R.string.please_select_entry)
            } else {
                analysisEvent(if (albumType == Album.TYPE_VIDEO) delete_video else delete_picture)
                viewModel.markDeleted(selected)
            }
        }
        binding.move.setOnClickCallback {
            val selected = adapter.selected
            if (selected.isEmpty()) {
                toast(R.string.please_select_entry)
            } else {
                AlbumMigrateDialogFragment.newInstance(albumType).show(supportFragmentManager)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        TransitionViewsRef.releaseTransitionViewRef(KEY_ENTRY)
    }

    private fun animToEditMode(entry: Entry? = null) {
        binding.editCancel.isVisible = true
        binding.selectAll.isVisible = true
        binding.bottomMenu.isVisible = true
        binding.add.isVisible = false
        binding.edit.isVisible = false
        binding.pageBack.isVisible = false
        adapter.enterEdit(entry)
    }

    private fun animToNormalMode() {
        binding.editCancel.isVisible = false
        binding.selectAll.isVisible = false
        binding.bottomMenu.isVisible = false
        binding.add.isVisible = true
        binding.edit.isVisible = true
        binding.pageBack.isVisible = true
        adapter.exitEdit()
    }

    private fun showViewer(clicked: Entry?) {
        if (clicked == null) return
        if (!binding.edit.isVisible) return

        when (albumType) {
            Album.TYPE_PICTURE -> asyncAnalysisEvent { "${view_picture}_${AlbumRepository.get().totalCount(albumType)}" }
            Album.TYPE_VIDEO -> asyncAnalysisEvent { "${view_video}_${AlbumRepository.get().totalCount(albumType)}" }
        }

        if (self.isVip) {
            ViewerHelper.provideImageViewerBuilder(
                this, KEY_ENTRY, clicked, dataList ?: listOf()
            ).show()
        } else {
            val idx = dataList?.indexOf(clicked) ?: Int.MAX_VALUE
            if (idx >= freeLimitCount) {
                when (albumType) {
                    Album.TYPE_PICTURE -> toast(String.format(getString(R.string._free_count_picture), freeLimitCount.toString()))
                    Album.TYPE_VIDEO -> toast(String.format(getString(R.string._free_count_video), freeLimitCount.toString()))
                }
                VipHelper.showBuyDialog("limitCount_$freeLimitCount", this)
            } else {
                val data = dataList ?: listOf()
                val displayList = data.subList(0, min(data.size, freeLimitCount))
                ViewerHelper.provideImageViewerBuilder(
                    this, KEY_ENTRY, clicked, displayList
                ).show()
            }
        }
    }

    companion object {
        private const val EXTRA_ALBUM_TYPE = "albumType"
        private const val EXTRA_ALBUM_ID = "albumId"
        fun start(context: Context?, albumId: Int?, albumType: Int?) {
            if (context == null || albumId == null || albumType == null) return
            context.startActivity(Intent(context, EntryActivity::class.java).apply {
                putExtra(EXTRA_ALBUM_ID, albumId)
                putExtra(EXTRA_ALBUM_TYPE, albumType)
            })
        }
    }
}
